﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using DTO;

namespace DAO
{
    public static class TaiKhoanDAO
    {
        public static bool Change(TaiKhoanDTO entity)
        {
            bool result = false;
            SqlConnection connection = new SqlConnection(DataProvider.ConnectionSting);
            try
            {
                SqlCommand command = new SqlCommand("sp_UpdateUser", connection);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@username", SqlDbType.NVarChar).Value = entity.Username;
                command.Parameters.Add("@password", SqlDbType.NVarChar).Value = entity.Password;
                connection.Open();

                if (command.ExecuteNonQuery() != 0)
                {
                    result = true;
                    entity.Password = "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
            }
            return result;
        }

        public static bool Check(TaiKhoanDTO entity)
        {
            bool result = false;
            SqlConnection connection = new SqlConnection(DataProvider.ConnectionSting);
            try
            {
                SqlCommand command = new SqlCommand("sp_SignIn", connection);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@username", SqlDbType.NVarChar).Value = entity.Username;
                command.Parameters.Add("@password", SqlDbType.NVarChar).Value = entity.Password;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        result = true;
                        entity.IsAdmin = true;
                        entity.Password = "";                       
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();                    
                }
            }
            return result;
        }

    }
}
